package com.woniuxy.service.impl;

import cn.hutool.core.lang.func.VoidFunc1;
import cn.hutool.crypto.SecureUtil;
import com.nimbusds.jose.JOSEException;
import com.woniuxy.entity.Address;
import com.woniuxy.entity.Food;
import com.woniuxy.entity.User;
import com.woniuxy.entity.UserCart;
import com.woniuxy.mapper.UserMapper;
import com.woniuxy.service.UserService;
import com.woniuxy.util.GetUserIdFromToken;
import com.woniuxy.util.JWTUtil;
import com.woniuxy.util.ResponseData;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: pigTrotterStore
 * @BelongsPackage: com.woniuxy.service
 * @Author: Quan
 * @Date: 2025/3/10 17:57
 */
@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {
	private UserMapper userMapper;

//	private StringRedisTemplate redisTemplate;

//	private Integer getUserIdFromJwt;

	private RedisTemplate<String, Object> redisTemplate;
	/**
	 * 1、根据用户进行查询
	 * 为空：返回
	 * 不为空，继续进行
	 * 2、对user密码进行加密后进行比对
	 * 不成功，返回null
	 * 成功，继续进行
	 * 3、创建jwt
	 *
	 * @param user
	 * @return
	 */
	@Override
	public ResponseData<?> login(User user) throws JOSEException {
		User userInfo = userMapper.queryInfo(user);
		if (userInfo == null) {
			return null;
		}

		String md5PWD = SecureUtil.md5(user.getPassword() + "1a2b3c4d");
		if (!userInfo.getPassword().equals(md5PWD)) {
			return null;
		}

		Map<String, Object> userMap = new HashMap<>();
		userMap.put("id", userInfo.getId());
		userMap.put("account", userInfo.getAccount());
		String jwt = JWTUtil.createJWT(userMap);

		// 将jwt存入数据库中
		redisTemplate.opsForValue().set("JWT:" + userInfo.getId(), jwt, 20, TimeUnit.DAYS);


		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("userInfo", userInfo);
		resultMap.put("jwt", jwt);

		return ResponseData.ok(resultMap);
	}

	/**
	 * 根据userId,foodId,status共同查询购物车中是否有该商品数据
	 * 		没有该商品数据:添加商品到购物车即可
	 * 		有该商品数据:
	 * 			需要将该商品的购买次数进行加和
	 * @return
	 */
	public ResponseData<?> addCart(Integer foodId, Integer buyNum) throws ParseException {
		// 通过userId,foodId,status查询未付钱的商品信息
		UserCart userCart = new UserCart();
		// 	获取userId
		Integer userId = GetUserIdFromToken.getUserId();
		userCart.setUserId(userId);
		userCart.setFoodId(foodId);
		// 对商品数据进行查询
		UserCart userCartInfo = userMapper.queryCartByInfo(userCart);
		// 如果商品不存在，直接添加数据
		// 准备数据
		userCart.setBuyNum(userCartInfo == null ? buyNum : userCartInfo.getBuyNum() + buyNum);
		userCart.setBuyPrice(((Food)(redisTemplate.opsForHash().get("CHARE:FOODSERVICEIMPL:QUERYFOODDETAIL", foodId.toString()))).getSellPrice());
		userCart.setTotalPrice(BigDecimal.valueOf(userCart.getBuyNum()).multiply(userCart.getBuyPrice()));

		if (userCartInfo == null) {
			// 添加该商品到购物车中
			userMapper.addCartFromUser(userCart);
		} else {
			userCart.setId(userCartInfo.getId());
			// 说明该商品之前存在，只需要对数据进行修改即可
			userMapper.updateCart(userCart);
		}
		return ResponseData.ok();
	}

	/**
	 * @Description: 查询用户的订单和地址
	 * @Param:
	 * @Author: Quan
	 * @Date: 2025/3/13
	*/
	@Override
	public ResponseData<?> queryUserCartAndAddr() throws ParseException {
		// 获取用户id
		Integer userId = GetUserIdFromToken.getUserId();
		// 通过用户id查询地址
		List<Address> addresses = userMapper.queryAddressByUserId(userId);
		// 通过用户id获取订单
		List<UserCart> userCarts = userMapper.queryUserCartByUserId(userId);
		Map<String, Object> map = new HashMap<>();
		map.put("addresses", addresses);
		map.put("userCarts", userCarts);
		return ResponseData.ok(map);
	}
}
